// map options
var mapOptions = {
  minZoom: 5,
  //mapType: BMAP_HYBRID_MAP
  //mapType: BMAP_NORMAL_MAP
  mapType: BMAP_SATELLITE_MAP
}
var map = new BMap.Map("container", mapOptions);
var initPoint = new BMap.Point(116.352634, 39.985821);
var geoc = new BMap.Geocoder();

map.centerAndZoom(initPoint,18);
/*map.enableScrollWheelZoom();*/
map.enableKeyboard();
map.enableContinuousZoom();
map.enableDragging();
map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_RIGHT, offset: new BMap.Size(20,80)}));

// panel.js
//雷达图，圆盘、飞机、扇面分别用三个不同的canvas绘制（有了矢量图之后直接js修改css，transform样式）
var circle = {
  x : 70,
  y : 70,
  r : 20      //最小圆的半径
};
// 画圆圈（固定的）
var canvas = document.getElementById("radarPic");
var ctx = canvas.getContext("2d");
ctx.lineWidth = 1;
// ctx.strokeStyle = "#00d5d3";
ctx.strokeStyle = "rgba(0,213,211,.55)";
ctx.translate(circle.x, circle.y);
ctx.beginPath();
ctx.arc(0, 0, circle.r-3, 0, Math.PI * 2, true);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, (circle.r+15), 0, Math.PI * 2, true);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, (circle.r+30), 0, Math.PI * 2, true);
//ctx.strokeStyle = "rgba(0,213,211,.55)";
ctx.stroke();
// ctx.beginPath();
// ctx.arc(0, 0, (circle.r+30), 0, Math.PI * 2, true);
// ctx.strokeStyle = "rgba(255,255,255,.35)";
// ctx.stroke();

// 画十字线  //var bp = 200 - Math.sqrt( 100*100/2 );//45度斜十字
var rmax = (circle.r+50);
ctx.beginPath();
ctx.moveTo(0,-rmax);
ctx.lineTo(0,rmax-10);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(-rmax,0);
ctx.lineTo(rmax,0);
ctx.stroke();

// 心跳包
var breath_container = document.getElementById("breathDiv");
var breath_div = document.createElement("DIV");
breath_div.setAttribute("id","radarBreath");
function breathe(){
  div_remove = breath_container.getElementsByTagName('DIV');
  breath_container.removeChild(div_remove[0]);
  breath_container.appendChild(breath_div);
}
//setInterval("breathe()",3000);

//绘制表示云台方向的扇形
var canvas_sec = document.getElementById("radarSector");
var ctx_sec = canvas_sec.getContext("2d");
var sec_axis = - Math.PI/2;//扇形对称轴变量
sector(sec_axis);//调用绘制扇形函数
function sector(sec_axis){
  //首先清空画布，然后重画
  ctx_sec.clearRect(0,0,140,140);
  ctx_sec.beginPath();
  ctx_sec.moveTo(circle.x, circle.y);
  // 绘制圆弧
  ctx_sec.arc(circle.x, circle.y, 100, sec_axis-1/6 * Math.PI, sec_axis+1/6 * Math.PI);
  // 闭合路径
  ctx_sec.closePath();
  //颜色渐变样式
  var my_gradient=ctx_sec.createRadialGradient(circle.x, circle.y, 0,circle.x, circle.y, 100);
  my_gradient.addColorStop(0.0,"#00d5d3");
  my_gradient.addColorStop(1,"transparent");
  ctx_sec.fillStyle=my_gradient;
  ctx_sec.fill();
}


//俯仰角变量
var up_down_angel = 30;
//倾斜角变量
var left_down_angel = 30;

//姿态球（地平仪）
var panel_r = 75;
var panel_d = 2*panel_r;
var canvas_bgcolor = document.getElementById("gesture-bgcolor");
var ctx_bgcolor = canvas_bgcolor.getContext("2d");
ctx_bgcolor.translate(panel_r, panel_r);
ctx_bgcolor.strokeStyle = "#5CACEE";
ctx_bgcolor.beginPath();
ctx_bgcolor.arc(0, 0, panel_r-15, 0, Math.PI * 2, true);
ctx_bgcolor.stroke();
ctx_bgcolor.fillStyle= "#5CACEE";
ctx_bgcolor.fill();
//
var canvas_color = document.getElementById("gesture-frontcolor");
var ctx_color = canvas_color.getContext("2d");
ctx_color.translate(panel_r, panel_r);
var lrImg = document.getElementById('lrImg');
//
var canvas_scale = document.getElementById("gesture-scale");
var ctx_scale = canvas_scale.getContext("2d");
var udImg = document.getElementById('udImg');
fillSky(0/180*Math.PI, 0/180*Math.PI);//第1个参数为左右偏移角度，第2个参数为俯仰角度，范围均为－PI～PI

function fillSky(x,y){
  ctx_color.clearRect(-panel_r,-panel_r,panel_d,panel_d);
  ctx_scale.clearRect(0,0,100,100);

  ctx_color.beginPath();
  var scale_offset = y/Math.PI*180*1.9;
  var scale_angel = Math.asin(scale_offset/(panel_r-15));
  if(scale_offset>-panel_r+15 && scale_offset<panel_r-15) ctx_color.arc(0, 0, panel_r-15, scale_angel, Math.PI-scale_angel);
  else if(scale_offset<=-panel_r+15) ctx_color.arc(0, 0, panel_r-15, 0, 2*Math.PI);
  //else if(y>90/180*Math.PI && y<=Math.PI || y<=-90/180*Math.PI && y>=-Math.PI) ctx.arc(0, 0, panel_r-15, Math.PI+y, 2*Math.PI-y,true);
  ctx_color.fillStyle= "#8B7355";
  ctx_color.fill();
  ctx_color.drawImage(lrImg,-lrImg.width/2-7,-lrImg.height/2-25);
  //ctx_color.drawImage(lrImg,-lrImg.width/2, -40);
  canvas_color.setAttribute("style","transform:rotate("+ x/Math.PI*180 +"deg)");

  ctx_scale.drawImage(udImg, 18, -322 + scale_offset);
  canvas_scale.setAttribute("style","transform:rotate("+ x/Math.PI*180 +"deg) translateY(20px)");
}

//速度仪表
// var canvas_speed_Z = document.getElementById("speed-canvas-Z");
// var ctx_Z = canvas_speed_Z.getContext("2d");
// ctx_Z.translate(30, 35);
// var canvas_speed_X = document.getElementById("speed-canvas-X");
// var ctx_X = canvas_speed_X.getContext("2d");
// ctx_X.translate(30, 35);
// drawSpeedPanel(ctx_Z,0);
// drawSpeedPanel(ctx_X,0);
// function drawSpeedPanel(ctx,speed){
//   ctx.clearRect(-30,-35,60,60);
//   speed=(speed>10)?10:speed;
//   var speedAngel = speed/10*(Math.PI/3*4);
//   ctx.beginPath();
//   ctx.moveTo(0,0);
//   ctx.arc(0, 0, 30, Math.PI*5/6, Math.PI*5/6 + speedAngel, false);
//   ctx.closePath();
//   ctx.fillStyle = '#5CACEE';
//   ctx.fill();
//   ctx.beginPath();
//   ctx.moveTo(0,0);
//   ctx.arc(0, 0, 30, Math.PI/6, Math.PI*5/6 + speedAngel, true);
//   ctx.closePath();
//   ctx.fillStyle = 'grey';
//   ctx.fill();
//   ctx.beginPath();
//   ctx.moveTo(0,0);
//   ctx.arc(0, 0, 22, 0, Math.PI * 2, false);
//   ctx.closePath();
//   ctx.fillStyle = 'black';
//   ctx.fill();
// }

//添加动画切换div
var video_div = document.getElementById("video");
var video_anti_container = document.getElementById('video-animation-anti-container');
var video_animation1 = document.createElement("DIV");
video_animation1.setAttribute("id","video-animation1");
var video_animation2 = document.createElement("DIV");
video_animation2.setAttribute("id","video-animation2");
var video_animation_anti = document.createElement("DIV");
video_animation_anti.setAttribute("id","video-animation-anti");
function video_animation(){
  document.getElementById('video-mini').style.display = "none";
  // document.getElementById('map-mini').style.display = "block";
  video_div.style.display = "block";
  div_rm = video_div.getElementsByTagName('DIV');
  video_div.removeChild(div_rm[1]);
  video_div.removeChild(div_rm[0]);
  video_div.appendChild(video_animation1);
  video_div.appendChild(video_animation2);
  // document.getElementById('video-animation-anti').style.display = "none";
}
function video_animation_reverse(){
  // document.getElementById('map-mini').style.display = "none";
  video_div.style.display = "none";
  document.getElementById('video-mini').style.display = "block";
  div_rm = video_anti_container.getElementsByTagName('DIV');
  video_anti_container.removeChild(div_rm[0]);
  video_anti_container.appendChild(video_animation_anti);
}
// setInterval("video_switch_button()","2000");
function video_switch_button(){
  if(video_div.style.display!="block"){
    video_animation();
    init_map_mini();
  }
  else{
    video_animation_reverse();
  }
}

// 进度条
// 响应进度
// progress_value("replay-progress", "100%");
function progress_value(id, value){ //进度条赋值
  document.getElementById(id).style.width = value;
}

//panel边缘过度曲线
var canvas_margin = document.getElementById("panel-left-margin");
var ctx = canvas_margin.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0,0,40,40);
ctx.beginPath();
ctx.moveTo(40, 0);
ctx.globalCompositeOperation = 'destination-out'
ctx.arc(40, 0, 40, Math.PI/2, Math.PI);
ctx.fill();

var canvas_margin = document.getElementById("panel-right-margin");
var ctx = canvas_margin.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0,0,40,40);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.globalCompositeOperation = 'destination-out'
ctx.arc(0, 0, 40, 0, Math.PI/2);
ctx.fill();

// ------------------------------
// map control
function MapType(){
  this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
  this.defaultOffset = new BMap.Size(20,380);
}
MapType.prototype = new BMap.Control();
var MAP_TYPE_DROP_SHOW = false;
MapType.prototype.initialize = function(map){
  var img = document.createElement('IMG');
  img.src = "images/icon/maptype.png";
  img.style.height = '40px';
  img.style.width = '40px';
  var div = document.createElement('div');
  div.appendChild(img);
  div.style.cursor = 'pointer';
  div.style.backgroundColor = 'transparent';
  div.onclick = function(e){
    if(MAP_TYPE_DROP_SHOW) map_type_drop.hide();
    else map_type_drop.show();
    MAP_TYPE_DROP_SHOW = !MAP_TYPE_DROP_SHOW;
  }
  map.getContainer().appendChild(div);
  return div;
}
var map_type = new MapType();
map.addControl(map_type);

function MapTypeDrop(){
  this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
  this.defaultOffset = new BMap.Size(20,430);
}
MapTypeDrop.prototype = new BMap.Control();
MapTypeDrop.prototype.initialize = function(map){
  var img1 = document.createElement('IMG');
  img1.src = "images/icon/maptype1.png";
  img1.style.height = '50px';
  img1.style.width = '50px';
  img1.style.borderRadius = '5px';
  var p1 = document.createElement('P');
  p1.innerHTML = '标准地图';
  p1.style.color = 'white';
  p1.style.width = '50px';
  p1.style.fontSize = '10px';
  p1.style.fontWeight = 'bold';
  p1.style.textAlign = 'center';
  var div1 = document.createElement('div');
  div1.style.height = '65px';
  div1.style.width = '50px';
  div1.style.padding = '5px';
  div1.style.float = 'left';
  div1.appendChild(img1);
  div1.appendChild(p1);
  var img2 = document.createElement('IMG');
  img2.src = "images/icon/maptype2.png";
  img2.style.height = '50px';
  img2.style.width = '50px';
  img2.style.borderRadius = '5px';
  var p2 = document.createElement('P');
  p2.innerHTML = '卫星地图';
  p2.style.color = 'white';
  p2.style.width = '50px';
  p2.style.fontSize = '10px';
  p2.style.fontWeight = 'bold';
  p2.style.textAlign = 'center';
  var div2 = document.createElement('div');
  div2.style.height = '65px';
  div2.style.width = '50px';
  div2.style.padding = '5px';
  div2.style.float = 'left';
  div2.appendChild(img2);
  div2.appendChild(p2);
  var img3 = document.createElement('IMG');
  img3.src = "images/icon/maptype2.png";
  img3.style.height = '50px';
  img3.style.width = '50px';
  img3.style.borderRadius = '5px';
  var p3 = document.createElement('P');
  p3.innerHTML = '混合地图';
  p3.style.color = 'white';
  p3.style.width = '50px';
  p3.style.fontSize = '10px';
  p3.style.fontWeight = 'bold';
  p3.style.textAlign = 'center';
  var div3 = document.createElement('div');
  div3.style.height = '65px';
  div3.style.width = '50px';
  div3.style.padding = '5px';
  div3.style.float = 'left';
  div3.appendChild(img3);
  div3.appendChild(p3);

  div1.style.cursor = 'pointer';
  div1.style.backgroundColor = 'transparent';
  div1.onclick = function(e){
    //每种地图的切换方法写在这里
    map.setMapType(BMAP_NORMAL_MAP);
    mapOptions.mapType = BMAP_NORMAL_MAP
    map_type_drop.hide();
    MAP_TYPE_DROP_SHOW = false;
  }
  div2.style.cursor = 'pointer';
  div2.style.backgroundColor = 'transparent';
  div2.onclick = function(e){
    map.setMapType(BMAP_SATELLITE_MAP);
    mapOptions.mapType = BMAP_SATELLITE_MAP
    map_type_drop.hide();
    MAP_TYPE_DROP_SHOW = false;
  }
  div3.style.cursor = 'pointer';
  div3.style.backgroundColor = 'transparent';
  div3.onclick = function(e){
    map.setMapType(BMAP_HYBRID_MAP);
    mapOptions.mapType = BMAP_HYBRID_MAP
    map_type_drop.hide();
    MAP_TYPE_DROP_SHOW = false;
  }

  var div = document.createElement('div');
  div.style.backgroundColor = '#374a52';
  div.style.borderRadius = '10px';
  div.appendChild(div1);
  div.appendChild(div2);
  div.appendChild(div3);
  map.getContainer().appendChild(div);
  return div;
}
var map_type_drop = new MapTypeDrop();
map.addControl(map_type_drop);
map_type_drop.hide();

function ZoomMap(){
  this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
  this.defaultOffset = new BMap.Size(20,140);
}
ZoomMap.prototype = new BMap.Control();
ZoomMap.prototype.initialize = function(map){
  var img = document.createElement('IMG');
  img.src = "images/icon/zoom.png";
  img.style.height = '40px';
  img.style.width = '40px';
  var div = document.createElement('div');
  div.appendChild(img);
  div.style.cursor = 'pointer';
  div.style.backgroundColor = 'transparent';
  div.onclick = function(e){
    map.setZoom(map.getZoom() + 1);
  }
  map.getContainer().appendChild(div);
  return div;
}
var zoom_map = new ZoomMap();
map.addControl(zoom_map);

function ReduceMap(){
  this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
  this.defaultOffset = new BMap.Size(20,220);
}
ReduceMap.prototype = new BMap.Control();
ReduceMap.prototype.initialize = function(map){
  var img = document.createElement('IMG');
  img.src = "images/icon/reduce.png";
  img.style.height = '40px';
  img.style.width = '40px';
  var div = document.createElement('div');
  div.appendChild(img);
  div.style.cursor = 'pointer';
  div.style.backgroundColor = 'transparent';
  div.onclick = function(e){
    map.setZoom(map.getZoom() - 1);
    /*uas.mission_cmd_mission_start();*/
  }
  map.getContainer().appendChild(div);
  return div;
}
var reduce_map = new ReduceMap();
map.addControl(reduce_map);

function say_msg(text){
  var msg = new SpeechSynthesisUtterance();
  msg.voiceURI = 'native';
  msg.volume = 1; // 0 to 1
  msg.lang = 'ch-CN';
  msg.text = text;
  speechSynthesis.speak(msg);
}

var uav_number = 'VCTFA166001';
var socket = io('http://123.124.17.230:3005');

socket.emit("web_join", uav_number)
request_gcs_waypoints();

socket.on("uav_msg", function(msg){
  /*console.log(msg);*/
  switch(msg.type){
    case 'heartbeat':
      on_heartbeat(msg.field);
      break;
    case 'gps_msg':
      on_gps_msg(msg.field);
      break;
    case 'bat_info':
      on_bat_info(msg.field);
      break;
    case 'reached':
      on_reached(msg.field);
      break;
    case 'gcs_waypoints':
      on_gcs_waypoints(msg.field);
      break;
    default:
      break;
  }
});

var uas_custom_mode = -1;
function on_heartbeat(field){
  if(field != undefined){
    breathe();
    var base_status = field;
    if(base_status.custom_mode == 3){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./icon/auto.png)'
      if(uas_custom_mode != -1 && uas_custom_mode != base_status.custom_mode) {
        say_msg("自主模式");
        console.log('自主模式');
      }
    }
    else if(base_status.custom_mode == 6){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./icon/rtl.png)'
      if(uas_custom_mode != -1 && uas_custom_mode != base_status.custom_mode) {
        say_msg("返航模式");
        console.log('返航模式');
      }
    }
    else if(base_status.custom_mode == 9){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./icon/land.png)'
      if(uas_custom_mode != -1 && uas_custom_mode != base_status.custom_mode) {
        say_msg("降落模式");
        console.log('降落模式');
      }
    }
    else if(base_status.custom_mode == 5){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./icon/manu.png)'
      if(uas_custom_mode != -1 && uas_custom_mode != base_status.custom_mode){
        say_msg("手动模式");
        console.log('手动模式');
      }
    }
    else{
      /*uas_set_mode(6);*/
    }
    uas_custom_mode = base_status.custom_mode;
    if(base_status.system_is_armed){
      document.getElementById("lock-button").style.backgroundImage = 'url(./icon/unlock-blue.png)'
    }
    else{
      document.getElementById("lock-button").style.backgroundImage = 'url(./icon/lock-blue.png)'
    }
  }
}

var plane_marker = null;
var mini_plane_marker = null;
var uas_is_armed = false;
function on_gps_msg(gps_msg){
  var hor_speed = gps_msg.hor_speed;
  var ver_speed = gps_msg.ver_speed;
  var lat = gps_msg.lat;
  var lon = gps_msg.lon;
  var height = gps_msg.height;
  var satellite_number = gps_msg.satellite_number;
  var overall_dis = gps_msg.overall_dis;
  var dis_from_home = gps_msg.dis_from_home;
  var hdop = gps_msg.hdop;
  var vdop = gps_msg.vdop;
  var attitude = gps_msg.attitude;
  /*var cur_position = new BMap.Point(bd09[0], bd09[1]);*/
  var cur_position = new BMap.Point(gps_msg.cur_position.lng, gps_msg.cur_position.lat);
  document.getElementById('panel-speedX').innerHTML = '' + hor_speed;
  document.getElementById('panel-speedZ-arrow').style.display = 'block';
  if(ver_speed >= 0.1) {
    document.getElementById('panel-speedZ-arrow').style.transform = "rotate(0deg)";
  }
  else if(ver_speed <= -0.1) {
    document.getElementById('panel-speedZ-arrow').style.transform = "rotate(180deg)";
  }
  else document.getElementById('panel-speedZ-arrow').style.display = 'none';
  document.getElementById('panel-speedZ').innerHTML = '' + Math.abs(ver_speed).toFixed(1);
  document.getElementById('panel-lat').innerHTML = '' + lat;
  document.getElementById('panel-lng').innerHTML = '' + lon;
  document.getElementById('panel-flightheight').innerHTML = '' + height;
  document.getElementById('panel-speedZ-pointer').setAttribute("style","transform:rotate("+ Math.abs(ver_speed)/12*180 +"deg)");
  document.getElementById('panel-speedX-pointer').setAttribute("style","transform:rotate("+ hor_speed/60*180 +"deg)");
  document.getElementById('satellite-number').innerHTML = '' + satellite_number;
  document.getElementById('panel-flightspan').innerHTML = '' + overall_dis.toFixed(1);
  document.getElementById('panel-flightdistance').innerHTML = '' + dis_from_home.toFixed(1);
  document.getElementById('panel-hdop').innerHTML = '' + hdop;
  document.getElementById('panel-vdop').innerHTML = '' + vdop;
  if(plane_marker == undefined || plane_marker == null){
    plane_marker = new BMap.Marker(cur_position);
    map.addOverlay(plane_marker);
    plane_marker.setIcon(plane_icon);
    plane_marker.setTop(true);
    plane_marker.setZIndex(1);
  }
  plane_marker.setPosition(cur_position);
  plane_marker.setRotation(attitude.yaw*180.0/Math.PI);
  if(uas_is_armed){
    update_track_line(cur_position);
  }
  // attitude ball
  document.getElementsByClassName('dial-circle')[0].setAttribute("style","transform: translateX(26px) scale(1.5) rotate("+ (- attitude.yaw/Math.PI*180) +"deg)");
  fillSky(attitude.roll, attitude.pitch);
  // radar
  document.getElementById('plane-rotate').setAttribute("style","transform:rotate("+ attitude.yaw/Math.PI*180 +"deg)");
  sector(attitude.yaw - Math.PI/2);
  // time since armed
  var time_since_armed = gps_msg.time_since_armed;
  document.getElementById('panel-flighttime').innerHTML = (time_since_armed/1000).toFixed(1) + 's';
  if(uas_is_armed !== gps_msg.uas_is_armed){
    if(gps_msg.uas_is_armed == true){
      clear_track_line();
      say_msg('飞行器已解锁');
      /*
      if(document.getElementById("play-drop").style.display == 'block'){
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/play-blue.png)'
      }
      else{
        document.getElementById("play-button").style.backgroundImage = 'url(./icon/play-grey.png)'
      }
      */
      /*document.getElementById('play-title').innerHTML = '进入自主航线飞行？';*/
      document.getElementById("lock-button").style.backgroundImage = "url('./icon/unlock-blue.png')";
      /*enable_nav_button("takeoff-button", true);*/
      /*enable_nav_button("rtl-button", true);*/
      /*enable_nav_button("land-button", true);*/
      /*enable_nav_button("play-button", true);*/
    }
    else{
      say_msg('飞行器已上锁');
      document.getElementById("lock-button").style.backgroundImage = "url('./icon/lock-blue.png')";
      /*enable_nav_button("takeoff-button", false);*/
      /*enable_nav_button("rtl-button", false);*/
      /*enable_nav_button("land-button", false);*/
      /*enable_nav_button("play-button", false);*/
    }
  }
  uas_is_armed = gps_msg.uas_is_armed;

}

function on_bat_info(field){
  var battery_level_measured = field.battery_level_measured;
  var bat_left_time = field.bat_left_time;
  var battery_vol_avg = field.battery_vol_avg;
  document.getElementById('panel-battery').innerHTML = '' + (battery_vol_avg).toFixed(1)
  if(battery_level_measured > 0.75){
    document.getElementById("battery-volume").src = './icon/battery-green.png';
  }
  else if(battery_level_measured > 0.50){
    document.getElementById("battery-volume").src = './icon/battery-blue.png';
  }
  else if(battery_level_measured > 0.25){
    document.getElementById("battery-volume").src = './icon/battery-orange.png';
  }
  else if(battery_level_measured > 0){
    document.getElementById("battery-volume").src = './icon/battery-red.png';
  }
  else{
    document.getElementById("battery-volume").src = './icon/battery.png';
  }
  document.getElementById('panel-lefttime').innerHTML = '' + bat_left_time;
  document.getElementById('panel-battery-percent').innerHTML = '' + (battery_level_measured*100).toFixed(0);
}

var reached_index = 0;
function on_reached(field){
  if(field == -1){
    request_gcs_waypoints();
  }
  else{
    say_msg("到达" + field + "号航点");
    reached_index = field;
    /*update_cur_point_info();*/
  }
}

function on_gcs_waypoints(field){
  clear_wp_on_map();
  gcs_waypoints_list = field;
  var marker_points = [];
  for(var i=0;i<gcs_waypoints_list.length;i++){
    var cur_wp = gcs_waypoints_list[i];
    var bd09 = wgs84tobd09(cur_wp.lng, cur_wp.lat);
    draw_new_wp(new BMap.Point(bd09[0], bd09[1]), i);
    if(i>0) marker_points.push(new BMap.Point(bd09[0], bd09[1]));
  }
  redraw_waypoint_polyline();
  cur_clicked_mark = gcs_waypoints_list.length - 1;
  map.setViewport(marker_points, {margins: [50, 50, 250, 300]});
  if(gcs_waypoints_list.length > 0){
    if(gcs_waypoints_list[0].lat >10 && gcs_waypoints_list[0].lng > 0){
      update_home(true, gcs_waypoints_list[0].lng, gcs_waypoints_list[0].lat);
    }
  }
}

// ------------------------------
// waypoints related
var waypoints_editable = false;
var gcs_waypoints_list = [];  // waypoint on gcs is different with uav_waypoint_list
var waypoint_markers_list = [];
var waypoint_polyline = null;
var waypoint_polyline_points_list = [];
var WP_ACTION_NOTHING = 0;
var WP_ACTION_LAND = 1;
var WP_ACTION_RTL = 2;
var WP_HOME_DEFAULT_LNG = 116.352634;
var WP_HOME_DEFAULT_LAT = 39.985821;
var WP_DEFAULT_YAW = 0;

var WP_DEFAULT_ALT = 20;
var WP_MAX_ALT = 1000;
var WP_MIN_ALT = 5;

var WP_DEFAULT_SPEED = 8;
var WP_MAX_SPEED = 20;
var WP_MIN_SPEED = 0;

var WP_DEFAULT_TIME = 0;
var WP_MIN_TIME = 0;
var WP_MAX_TIME = 3600;

var WP_DEFAULT_TAKEOFF_ALT = 10;
var WP_DEFAULT_TAKEOFF_ALT_MIN = 3;
var WP_DEFAULT_TAKEOFF_ALT_MAX = 100;
var wp_takeoff_alt = WP_DEFAULT_TAKEOFF_ALT;

var WP_DEFAULT_RTL_ALT = 20;
var WP_DEFAULT_RTL_ALT_MIN = 0;
var WP_DEFAULT_RTL_ALT_MAX = 80;
var wp_rtl_alt = WP_DEFAULT_RTL_ALT;

var WP_DEFAULT_RTL_SPEED = 8;
var WP_DEFAULT_RTL_SPEED_MIN = 0;
var WP_DEFAULT_RTL_SPEED_MAX = 20;
var wp_rtl_speed = WP_DEFAULT_RTL_SPEED;

var WP_DEFAULT_UP_SPEED = 2.5;
var WP_DEFAULT_UP_SPEED_MIN = 0;
var WP_DEFAULT_UP_SPEED_MAX = 10;
var wp_up_speed = WP_DEFAULT_UP_SPEED;

var WP_DEFAULT_DOWN_SPEED = 1.8;
var WP_DEFAULT_DOWN_SPEED_MIN = 0;
var WP_DEFAULT_DOWN_SPEED_MAX = 5;
var wp_down_speed = WP_DEFAULT_DOWN_SPEED;

var WP_DEFAULT_ACTION = WP_ACTION_NOTHING;
var cur_rtl_index = 0;
// home valid only true when
// 1. waypoints are transmitted from uav and that point is valid
// 2. copter armed on the ground
var home_valid = false;
var home_lng = WP_HOME_DEFAULT_LNG;
var home_lat = WP_HOME_DEFAULT_LAT;
var home_wp = new WayPoint(WP_HOME_DEFAULT_LAT, WP_HOME_DEFAULT_LNG, 0, WP_DEFAULT_YAW, WP_DEFAULT_ALT, WP_DEFAULT_SPEED, WP_DEFAULT_TIME, WP_ACTION_NOTHING);

// ------------------------------
// icons
var SPOT_SIZE = 40;
var point_icon = new BMap.Icon("icon/waypoint.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_dark = new BMap.Icon("icon/waypoint-dark.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_orange = new BMap.Icon("icon/waypoint-orange.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_dark.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_orange.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var wp_mark_offset = new BMap.Size(0,-20);
var PLANE_SIZE = new BMap.Size(35, 50);
var plane_icon = new BMap.Icon("icon/bat.png", PLANE_SIZE);
plane_icon.setImageSize(PLANE_SIZE);
var cur_clicked_mark = 0;// marker clicked
var cur_seq_mark = 0;
var MINI_PLANE_SIZE = new BMap.Size(15, 22);
var mini_plane_icon = new BMap.Icon("icon/bat.png", MINI_PLANE_SIZE);
mini_plane_icon.setImageSize(MINI_PLANE_SIZE);

function WayPoint(lat, lng, num, yaw, altitude, spd, hld_time, do_action){
  this.lat = lat;
  this.lng = lng;
  this.index = num;
  this.yaw = yaw;
  this.alt = altitude;
  this.speed = spd;
  this.hold_time = hld_time;
  this.action = do_action;
}

function  map_is_editable() {
  /*return document.getElementById("multi-drop").style.display=="block";*/
  return false;
  /*return true;*/
}

map.addEventListener("click",function(e){
  if(!marker_clicked && map_is_editable()){
    //console.log(bd09towgs84(e.point.lng, e.point.lat));
    if(gcs_waypoints_list.length == 0){
      gcs_waypoints_list.push(home_wp);
      var bd09 = wgs84tobd09(home_wp.lng, home_wp.lat);
      draw_new_wp(new BMap.Point(bd09[0], bd09[1]), 0);
    }
    var wgs84 = bd09towgs84(e.point.lng, e.point.lat);
    var gcs_wp = new WayPoint(wgs84[1], wgs84[0], gcs_waypoints_list.length, WP_DEFAULT_YAW, WP_DEFAULT_ALT, WP_DEFAULT_SPEED, WP_DEFAULT_TIME, WP_DEFAULT_ACTION);
    gcs_waypoints_list.push(gcs_wp);
    draw_new_wp(e.point, gcs_waypoints_list.length - 1);
    redraw_waypoint_polyline();
    /*marker_on_click(gcs_waypoints_list.length - 1);*/
    cur_clicked_mark = gcs_waypoints_list.length - 1;
    console.log(gcs_waypoints_list);
  }
  marker_clicked = false;
});


BMap.Marker.prototype.setIndex = function(index){
  this.wp_index = index;
}
BMap.Marker.prototype.getIndex = function(){
  return this.wp_index;
}

// boolean to indicate that marker has been clicked on top of map
// if ture, map won't action

var marker_clicked = false;
function draw_new_wp(point, index){
  var marker = new BMap.Marker(point);
  marker.setIcon(point_icon);
  marker.setOffset(wp_mark_offset);
  if(index < waypoint_markers_list.length){
    waypoint_markers_list.splice(index, 0, marker);
  }
  else{
    waypoint_markers_list.push(marker);
  }
  marker.setIndex(index);
  // marker.setTop(true);
  marker.setZIndex(1);
  marker_set_label(index);
  function on_dragging(e){
    // when dragging update waypoints location and redraw polyline
    /*
     var wgs84 = bd09towgs84(e.point.lng, e.point.lat);
     var gcs_wp = gcs_waypoints_list[marker.getIndex()];
     gcs_wp.lat = wgs84[1];
     gcs_wp.lng = wgs84[0];
     cur_clicked_mark = marker.getIndex();
     redraw_waypoint_polyline();
     */
  }
  if(marker.getIndex()==0){
    marker.disableDragging();
  }
  else{
    marker.enableDragging();
    marker.addEventListener('dragging', on_dragging);
    marker.addEventListener('dragstart', function(e){
      marker_dragged = true;
    });
    marker.addEventListener('dragend', function(e){
      marker_dragged = false;
    });
  }
  marker.addEventListener('click', function(e){
    if(map_is_editable()){
      if(all_points.checked){
        for(var i=0;i<point_edit_list.length;i++){
          point_edit_list[i].style.background="url('./icon/waypoint.png')";
          point_edit_list[i].style.backgroundSize="100% 100%";
          /*marker_on_click(cur_clicked_mark);*/
        }
        all_points.checked = false;
      }
      /*marker_on_click(marker.getIndex());*/
      cur_clicked_mark = marker.getIndex();
      console.log('marker clicked'+ marker.getIndex())
      marker_clicked = true;
    }
  });
  //redraw_waypoint_polyline();
  map.addOverlay(marker);
  // refresh multi points
  multi_refresh_points();
}

// add label to marker
function marker_set_label(index) {
  if(waypoint_markers_list[index] == undefined || index > waypoint_markers_list.length){
    return;
  }
  // clear old label
  var old_label = waypoint_markers_list[index].getLabel();
  if(old_label != null){
    old_label.setContent("");
  }
  // set new index
  waypoint_markers_list[index].setIndex(index);
  var font_size = 10;
  if(index<10){
    font_size = 18;
  }
  else if(index<100){
    font_size = 14;
  }
  else{
    font_size = 12;
  }
  if(index==0){
    var label = new BMap.Label('H',{offset:new BMap.Size(SPOT_SIZE/4-1,SPOT_SIZE/8)});
  }
  else{
    var label = new BMap.Label(index,{offset:new BMap.Size(SPOT_SIZE/4-1,SPOT_SIZE/8)});
  }
  label.setStyle({border: null, background: null, width: SPOT_SIZE/2+'px',  color : "white",textAlign:"center",verticalAlign: "middle",  fontSize : font_size+"px" }) ;
  waypoint_markers_list[index].setLabel(label);
}

// waypoint polyline method
var polyline = new BMap.Polyline([
], {strokeColor:"blue", strokeWeight:4, strokeOpacity:0.5});
map.addOverlay(polyline);
var home_line = new BMap.Polyline([
], {strokeColor:"blue", strokeWeight:4, strokeOpacity:0.8, strokeStyle:"dashed"});
map.addOverlay(home_line);
var rtl_line = new BMap.Polyline([
], {strokeColor:"blue", strokeWeight:4, strokeOpacity:0.8, strokeStyle:"dashed"});
map.addOverlay(rtl_line);

function redraw_waypoint_polyline(){
  var wp_distance = 0;
  var wp_time = 0;
  polyline.hide();
  home_line.hide();
  rtl_line.hide();
  waypoint_polyline_points_list = null;
  waypoint_polyline_points_list = [];
  for (var i=1;i<waypoint_markers_list.length;i++){
    waypoint_polyline_points_list.push(waypoint_markers_list[i].getPosition());
    if(waypoint_polyline_points_list.length >= 2){
      var src = waypoint_polyline_points_list.length - 2;
      var dst = waypoint_polyline_points_list.length - 1;
      var cur_dis = map.getDistance(waypoint_polyline_points_list[src], waypoint_polyline_points_list[dst]);
      if(i >=2 && i < gcs_waypoints_list.length){
        wp_time += cur_dis/gcs_waypoints_list[i-1].speed;
      }
      wp_distance += cur_dis;
    }
    if(gcs_waypoints_list[i] != undefined){
      if(gcs_waypoints_list[i].action == WP_ACTION_LAND || gcs_waypoints_list[i].action == WP_ACTION_RTL){
        if(gcs_waypoints_list[i].action == WP_ACTION_RTL){
          cur_rtl_index = i;
        }
        break;
      }
    }
  }
  polyline.setPath(waypoint_polyline_points_list);
  polyline.show();
  //console.log("redraw_waypoint_polyline"+waypoint_markers_list.length)
  // WP_DEFAULT_SPEED
  if(waypoint_markers_list.length > 0){
    if(home_valid){
      if(waypoint_markers_list.length > 1 && gcs_waypoints_list.length > 1){
        var home_line_point_list = [waypoint_markers_list[0].getPosition(), waypoint_markers_list[1].getPosition()];
        var home_line_dis = map.getDistance(waypoint_markers_list[0].getPosition(), waypoint_markers_list[1].getPosition());
        wp_time += home_line_dis/WP_DEFAULT_SPEED;
        wp_distance += home_line_dis;
        home_line.setPath(home_line_point_list);
        home_line.show();
      }
      if(waypoint_markers_list.length > 1 && cur_rtl_index > 0 && cur_rtl_index < gcs_waypoints_list.length && gcs_waypoints_list[cur_rtl_index].action == WP_ACTION_RTL){
        var rtl_line_point_list = [waypoint_markers_list[0].getPosition(), waypoint_markers_list[cur_rtl_index].getPosition()];
        var rtl_line_dis = map.getDistance(waypoint_markers_list[0].getPosition(), waypoint_markers_list[cur_rtl_index].getPosition());
        wp_time += rtl_line_dis/WP_DEFAULT_SPEED;
        wp_distance += rtl_line_dis;
        rtl_line.setPath(rtl_line_point_list);
        rtl_line.show();
      }
      waypoint_markers_list[0].show();
    }
    else{
      waypoint_markers_list[0].hide();
    }
  }
  for (var i=1;i<waypoint_markers_list.length;i++){
    if(gcs_waypoints_list[i].hold_time > 0){
      /*wp_time += gcs_waypoints_list[i].hold_time;*/
    }
  }

  /*document.getElementById("forecast-dis").innerHTML = wp_distance.toFixed(0) + "m";*/
  /*document.getElementById("totalJourney").innerHTML = wp_distance.toFixed(0) + "m";*/
  /*document.getElementById("forecast-time").innerHTML = wp_time.toFixed(0) + "s";*/
  /*document.getElementById("totalFlyTime").innerHTML = wp_time.toFixed(0) + "s";*/
}

// track polyline
var track_line = new BMap.Polyline([
], {strokeColor:"#ed1941", strokeWeight:3, strokeOpacity:0.75});
map.addOverlay(track_line);
var track_line_points = [];

var track_line_mini = new BMap.Polyline([
], {strokeColor:"#ed1941", strokeWeight:8, strokeOpacity:0.75});

function update_track_line(point){
  track_line_points.push(point);
  track_line.setPath(track_line_points);
  track_line.show();
}

function clear_track_line(){
  for(var i=0;i<track_line_points.length;i++){
    track_line_points[i] = null;
  }
  track_line_points = null;
  track_line_points = [];
  track_line.hide();
}

function clear_wp_on_map(){
  gcs_waypoints_list = null;
  gcs_waypoints_list = [];
  clean_markers();
  /*multi_refresh_points();*/
}

function clean_markers(){
  for(var i=0;i<waypoint_markers_list.length;i++){
    map.removeOverlay(waypoint_markers_list[i]);
    waypoint_markers_list[i] = null;
  }
  waypoint_markers_list = null;
  waypoint_markers_list = [];
  cur_clicked_mark = 0;
  redraw_waypoint_polyline();
}

function update_home(valid, lng, lat){
  if(home_wp == undefined || home_wp == null) return;
  if(valid){
    home_valid = true;
    home_wp.lat = lat;
    home_wp.lng = lng;
    if(waypoint_markers_list.length > 0){
      var bd09 = wgs84tobd09(lng, lat);
      waypoint_markers_list[0].setPosition(new BMap.Point(bd09[0], bd09[1]));
    }
  }
  else{
    home_valid = false;
    home_wp.lat = WP_HOME_DEFAULT_LAT;
    home_wp.lng = WP_HOME_DEFAULT_LNG;
    if(waypoint_markers_list.length > 0){
      var bd09 = wgs84tobd09(WP_HOME_DEFAULT_LNG, WP_HOME_DEFAULT_LAT);
      waypoint_markers_list[0].setPosition(new BMap.Point(bd09[0], bd09[1]));
    }
  }
  redraw_waypoint_polyline();
}

// copied from button.js
function markers_enbale_dragging(enabled) {
  if(enabled){
    for(var i=0;i<waypoint_markers_list.length;i++){
      waypoint_markers_list[i].enableDragging();
    }
  }
  else{
    for(var i=0;i<waypoint_markers_list.length;i++){
      waypoint_markers_list[i].disableDragging();
    }
  }
}

//航点在航点飞行面板显示
var point_edit_list = [];
/*var multi_input=document.getElementById("flightpoint-area");*/
function multi_refresh_points(){
  //取得div标签
  /*
   for(var i=1;i<point_edit_list.length;i++){
   var imgDiv = point_edit_list[i];
   multi_input.removeChild(imgDiv);
   }
   point_edit_list = [];
   var imgDiv = null;
  //创建要添加的DIV标签
  for(var i=0;i<gcs_waypoints_list.length;i++){
  draw_new_point(i);
  }
  */
}

function request_gcs_waypoints(){
  send_uav_msg('request_gcs_waypoints', 'hi');
}

function send_uav_msg(type, field){
  if(socket != null){
    var message = {
      id:uav_number,
      type:type,
      field:field
    }
    socket.emit("uav_msg", message);
  }
}

function enable_nav_button(id, enabled){
  var item = document.getElementById(id);
  if(enabled){
    item.disabled = false;
    var picname = item.id.substring(0,item.id.indexOf('-')+1)+"grey";
    item.style.backgroundImage = "url('icon/"+picname+".png')";
  }
  else{
    var picname = item.id.substring(0,item.id.indexOf('-')+1)+"none";
    item.style.backgroundImage = "url('icon/"+picname+".png')";
    reset_button(id.substring(0,id.indexOf('-')));
    item.disabled = true;
  }
}

function reset_button(prefix){
  document.getElementById(prefix + '-drop').style.display = 'none';
  document.getElementById(prefix + '-li').style.backgroundColor = "black";
}
